package com.zr.rocketmq.producer;

import com.zr.rocketmq.entity.Order;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

@RocketMQTransactionListener
public class OrderTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private OrderService orderService;

    /**
     * 执行本地事务
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        try {
            // 获取订单ID
            String orderId = (String) arg;

            // 执行本地事务：创建订单
            boolean result = orderService.createOrder(orderId);

            // 根据本地事务结果返回不同状态
            if (result) {
                return RocketMQLocalTransactionState.COMMIT; // 提交事务
            } else {
                return RocketMQLocalTransactionState.ROLLBACK; // 回滚事务
            }
        } catch (Exception e) {
            // 异常情况返回UNKNOWN，等待回查
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }

    /**
     * 事务回查
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        // 从消息中获取订单ID
        Order order = (Order) msg.getPayload();
        String orderId = order.getOrderId();

        // 查询订单状态
        String status = orderService.getOrderStatus(orderId);

        // 根据查询结果返回不同状态
        if ("CREATED".equals(status)) {
            return RocketMQLocalTransactionState.COMMIT;
        } else if ("NOT_EXIST".equals(status)) {
            return RocketMQLocalTransactionState.ROLLBACK;
        } else {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
